package com.example.dianproject.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用不加密的密码编码器
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors().and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 允许访问静态资源和API
            .antMatchers(
                "/",
                "/css/**",
                "/js/**",
                "/images/**",
                "/fonts/**",
                "/login.html",
                "/register.html",
                "/admin/**",      // 管理员页面
                "/meter-reader/**", // 抄表员页面
                "/customer/**",    // 客户页面
                "/api/auth/**",    // 认证API
                "/api/customer/**", // 客户API
                "/api/customers/**", // 客户管理REST接口
                "/api/electricity-price/**", // 电价API
                "/api/meters/**",   // 电表管理API
                "/api/meter-readings/**"  // 抄表记录API
            ).permitAll()
            .anyRequest().authenticated();
        
        return http.build();
    }
} 